package com.ztorn.controller;

import com.ztorn.dtos.ApiResult;
import com.ztorn.dtos.LoginRequest;
import com.ztorn.model.TWarehouse;
import com.ztorn.model.User;
import com.ztorn.services.UserService;
import com.ztorn.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
@Slf4j
public class UserController {

    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtil;
    private final PasswordEncoder passwordEncoder;
    private final UserService userService;

    public UserController(AuthenticationManager authenticationManager,JwtUtils jwtUtil , PasswordEncoder passwordEncoder,UserService userService) {
        this.authenticationManager = authenticationManager;
        this.jwtUtil = jwtUtil;
        this.passwordEncoder = passwordEncoder;
        this.userService = userService;
    }

//    @RequestMapping("/login")
//    public ResponseEntity<?> user(@RequestBody LoginRequest loginRequest) {
//        return ResponseEntity.ok("success");
//    }
    @RequestMapping("/register")
    public ResponseEntity<?> register(@RequestBody LoginRequest loginRequest) {
        log.info("register" + loginRequest);
        User user = new User();
        user.setAccount(loginRequest.getAccount());
        user.setPassword(passwordEncoder.encode(loginRequest.getPassword()));
        userService.save(user);
        return ResponseEntity.ok("register success");
    }

    @RequestMapping("/whse")
    public ApiResult getWareHouseByUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        User user = (User)principal;
        TWarehouse wareHouseByUserId = userService.getWareHouseByUserId(user.getAccount());
        return ApiResult.ok(wareHouseByUserId);
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("1111"));
    }
}
